/**
 * @description: lru - latestRecentUsed - 最近使用
 * @author: huen2015
 *
 */

import { deepClone } from './014-$-deepClone'

class Lru<TKey, TValue> {
	private lruMap: Map<TKey, TValue>
	constructor(private maxLength: number = 2) {
		this.lruMap = new Map()
	}

	getLru(): Lru<TKey, TValue> {
		return deepClone(this.lruMap)
	}

	get(key: TKey): TValue | null {
		if (this.lruMap.has(key)) {
			const value = this.lruMap.get(key) as TValue
			this.lruMap.delete(key)
			this.lruMap.set(key, value)
			return value
		} else {
			return null
		}
	}

	set(key: TKey, value: TValue): Lru<TKey, TValue> {
		if (this.lruMap.has(key)) {
			this.lruMap.delete(key)
			this.lruMap.set(key, value)
		} else {
			this.lruMap.set(key, value)

			if (this.lruMap.size > this.maxLength) {
				this.lruMap.delete(this.lruMap.keys().next().value)
			}
		}

		return this
	}
}

const lru = new Lru<string, string>()
lru.set('1', '1').set('2', '2')
console.info('lru', lru.getLru()) // {'1' => '1', '2' => '2'}
lru.get('1')
console.info('lru', lru.getLru()) // {'2' => '2', '1' => '1'}
lru.get('3')
console.info('lru', lru.getLru()) // {'2' => '2', '1' => '1'}
lru.set('3', '3')
console.info('lru', lru.getLru()) // {'1' => '1', '3' => '3'}
